import { URLSearchParams } from "url";
import {
    setFormData,
    setSingleTypeObject,
    singleTypeObject,
} from "./singleTypeObject";

/** Request 中的 body 的类型对象 */
export type BodyTypes =
    | {
          type: "plain";
          data: string;
      }
    | {
          type: "urlencoded";
          data: singleTypeObject<string> | URLSearchParams;
      }
    | {
          type: "json";
          data: Object;
      }
    | {
          type: "binary";
          data: Blob | File;
      }
    | {
          type: "arraybuffer";
          data: BufferSource;
      }
    | {
          type: "buffer";
          data: Buffer;
      }
    | {
          type: "form";
          data: Object | FormData;
      };

/* 接收类型对象并转化为 Request 的正常对象的方式 */
export const bodyTransform = (body?: BodyTypes): BodyInit | undefined => {
    if (!body) return;
    switch (body.type) {
        case "form":
            if (!(body.data instanceof FormData)) {
                return setFormData(new FormData(), body.data);
            }
        /** 穿透 */
        case "json":
            return JSON.stringify(body.data);
        case "urlencoded":
            if (!(body.data instanceof URLSearchParams)) {
                return setSingleTypeObject(new URLSearchParams(), body.data);
            }
        /** 穿透 */
        default:
            return body.data as BodyInit;
    }
};
